package com.hyving.home.httpclientdemo.config;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


@Component
public class HttpClientUtils {

    @Autowired
    private PoolingHttpClientConnectionManager cm;

    @Autowired
    private RequestConfig rc;

    public List<Header> basicHeaders(){
        List<Header> headers = new ArrayList<>();
        headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.16 Safari/537.36"));
        headers.add(new BasicHeader("Accept-Encoding", "gzip,deflate"));
        headers.add(new BasicHeader("Accept-Language", "zh-CN"));
        headers.add(new BasicHeader("Connection", "Keep-Alive"));
        headers.add(new BasicHeader("Content-type", "application/json;charset=UTF-8"));
        return headers;
    }

    public CloseableHttpClient getClient(){
        CloseableHttpClient build = HttpClientBuilder.create()
                .setDefaultRequestConfig(rc)
                .setConnectionManager(cm)
                .setDefaultHeaders(basicHeaders())
                // 保持长连接配置，需要在头添加Keep-Alive
//                .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())
                // 重试次数，默认是3次，没有开启
//                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, true))
                .build();
        return build;
    }



    public HttpEntity exec(String url) throws UnsupportedEncodingException {
        CloseableHttpClient client = getClient();

//        HttpGet http = new HttpGet(url);
        //post
        HttpPost http = new HttpPost(url);
        http.setHeader("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36");

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("scope","project"));
        params.add(new BasicNameValuePair("q","httpClient"));

        //使用封装的请求参数的List集合,创建表单实体对象
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf-8");
        http.setEntity(formEntity);


        CloseableHttpResponse httpResponse = null;
        HttpEntity entity =null;
        try {
            httpResponse = client.execute(http);

            if(200 == httpResponse.getStatusLine().getStatusCode()){
                entity = httpResponse.getEntity();
                System.out.println("请求返回数据内容：" + EntityUtils.toString(entity));
            }else{
                //todo 错误提示
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(httpResponse != null){
                //执行httpResponse.close关闭对象会关闭连接池，
                //如果需要将连接释放到连接池，可以使用EntityUtils.consume()方法
                try {
                    EntityUtils.consume(httpResponse.getEntity());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return entity;
    }
}
